<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/funcs.php';
require_once __DIR__ . '/Lib/Page.php';

checkLogin();

// 权限检查
$funcs = getFuncs($_SESSION['admin_group']);
checkFunc(9900);

$now = time();
$success = $_GET['success'] ?? null;
$error = $_GET['error'] ?? null;
$action = $_GET['action'] ?? null;

if($action) {
	if($action == 'new_group') {
        $name = $_GET['name'] ?? '';
        $funcs = $_GET['funcs'] ?? '';
        if(!$name) $error = '组名不可为空';
        else {
            try {
                $DB->insert('admin_groups', ['name' => $name, 'funcs' => $funcs]);
                $gp_id = $DB->id();
            } catch(\Exception $e) {
                $error = '组名已存在,创建失败';
            }
            $success = '分组创建成功';
	        operate_log('super', 'new_group', ['组ID' => $gp_id, '名称' => $name, '功能' => $funcs]);
        }
	}
	else if($action == 'del') {
	    $gid = $_GET['gid'] ?? null;
	    if(!$gid) $error = '分组ID为空';
	    else {
	        $DB->delete('admin_groups', ['id'=>$gid]);
	        $success = '分组删除成功';
		    operate_log('super', 'delete_group', ['组ID' => $gid]);
        }
    }
	else {
		$error = '无效的操作';
	}
    goExit('super_group.php?success=' . $success . '&error=' . $error);
}

$all_group = $DB->select('admin_groups', '*');
$all_admin = $DB->select('admin_user', ['id','groupid']);
$group_user_nums = [];
foreach($all_admin as $a) {
    @$group_user_nums[$a['groupid']]++;
}

$all_funcs = [];
$func_ids = [];
$get_funcs = $DB->select('admin_funcs', '*');
foreach($get_funcs as $func) {
	$desc_arr = explode('-', $func['desc']);
	$all_funcs[$desc_arr[0]][$desc_arr[1]][$desc_arr[2]] = $func['id'];
	$func_ids[] = $func['id'];
}

display_header();
?>

<style>
    .data_table th {font-size:14px; color:#666; font-weight:normal; width:180px;}
    .data_table td {font-size:18px; font-weight:normal;text-align:right;}
    .data_table td small {font-size:12px; color:#888;margin-left:3px;}
    .data_table td div {padding:0;}
    td,th {vertical-align:middle !important;}
    .filter_box span {border:1px solid #4b97c4; border-radius:5px; padding:4px 7px; margin-right:10px;}
    .modal_table_style td {font-size:16px;}
    .funcs_box {}
    .funcs_box label {font-weight:normal;}
    .funcs_box input {margin:0; padding:0;}
</style>

<section class="content">

	<?php if($error) : ?>
		<div class="alert alert-warning alert-dismissible">
			<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
			<span><?php echo $error; ?></span>
		</div>
	<?php endif ?>
	<?php if($success) : ?>
		<div class="alert alert-success alert-dismissible">
			<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
			<h4><i class="icon fa fa-check"></i> 成功</h4>
			<?php echo $success; ?>
		</div>
	<?php endif ?>

	<div class="box box-primary">
		<div class="box-header with-border">
			<h3 class="box-title"><i class="fa fa-search"></i> 分组列表</h3>
		</div>

		<div class="box-body" id="vbody">

			<button type="button" class="btn btn-primary pull-left" style="margin-bottom:10px;" data-toggle="modal" data-target="#modal-add-admin">添加新的分组</button>

			<table id="logtable" class="table table-bordered table-striped dataTable table-hover " role="grid" aria-describedby="example1_info">
				<thead>
				<tr>
					<th class="" rowspan="1" colspan="1" width="100" style="text-align:center;">组ID</th>
					<th class="" rowspan="1" colspan="1" width="120" style="text-align:center;">组名</th>
					<th class="" rowspan="1" colspan="1" width="150" style="text-align:center;">权限数量</th>
                    <th class="" rowspan="1" colspan="1" width="150" style="text-align:center;">下属用户数</th>
					<th class="" rowspan="1" colspan="1" style="text-align:center">操作</th>
				</tr>
				</thead>
				<tbody>
				<?php if(!empty($all_group)) { foreach($all_group as $group) { ?>
					<tr role="row" style="text-align:center;">
						<td><?php echo $group['id']; ?></td>
						<td><?php echo $group['name']; ?></td>
						<td><?php echo count(explode(',', $group['funcs'])); ?></td>
                        <td><?php echo $group_user_nums[$group['id']] ?? 0; ?></td>
						<td style="text-align:left;">
                            <button type="button" class="btn btn-sm btn-success"
                                    data-toggle="modal" data-target="#modal-funcs-detail"
                                    v-on:click="funcsDetail('<?=$group['name']?>', '<?=$group['funcs']?>')"
                            >查看详细权限</button> |
                            <button type="button" class="btn btn-sm btn-danger del_notice" v-on:click="delGroup('<?=$group['id']?>', '<?php echo $group_user_nums[$group['id']] ?? 0; ?>')">删除分组</button>
						</td>
					</tr>
				<?php } } ?>
				</tbody>
			</table>

			<!-- 添加分组弹框 -->
			<div class="modal fade" id="modal-add-admin">
				<div class="modal-dialog modal-lg">
					<div class="modal-content">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">&times;</span></button>
							<h4 class="modal-title">添加新的分组</h4>
						</div>
						<div class="modal-body">
							<table border="0" width="100%" class="modal_table_style">
								<tr height="45">
									<th style="text-align:right;padding-right:10px;">分组名:</th>
									<td><input type="text" class="form-control" size="20" v-model="new_group_name" /></td>
								</tr>
								<tr height="45">
									<th style="text-align:right;padding-right:10px;">组内权限:<br /><span style="font-size:12px;color:#999;">可额外选择权限<br />也可取消组内默认权限</span></th>
									<td style="font-size:12px;">
										<div class="funcs_box" style="overflow-y:scroll;height:300px;padding:5px 10px; margin:10px 0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;border-left:1px solid #ccc;">
                                        <?php
                                        foreach($all_funcs as $cate_1 => $f) {
                                            echo '<div style="font-size:14px;font-weight:bold;margin-bottom:1px;">' . $cate_1 . '</div>';
                                            foreach($f as $cate_2 => $ff) {
                                                echo '<div style="border-bottom:1px solid #eee;margin:0;padding:0;margin-bottom:1px;">';
	                                            echo '<div style="width:150px;" class="pull-left">　　|—　' . $cate_2 . '</div>';
	                                            echo '<div class="pull-left">';
	                                            foreach($ff as $cate_3 => $fff) {
		                                            echo '<label style="margin-right:15px;display:inline-block;">';
		                                            echo '<input type="checkbox" class="minimal" v-model="new_group_funcs" value="'.$fff.'"> ';
		                                            echo $cate_3;
		                                            echo '</label>';
	                                            }
	                                            echo '</div>';
	                                            echo '<div style="clear:both"></div>';
                                                echo '</div>';
                                            }
                                        }
                                        ?>
                                        </div>
									</td>
								</tr>
							</table>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
							<button type="button" class="btn btn-primary" v-on:click="submitAddGroup">确定</button>
						</div>
					</div>
				</div>
			</div>

            <!-- 查看分组详细权限弹框 -->
            <div class="modal fade" id="modal-funcs-detail">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">分组详细权限</h4>
                        </div>
                        <div class="modal-body">
                            <table border="0" width="100%" class="modal_table_style">
                                <tr height="45">
                                    <th style="text-align:right;padding-right:10px;">分组名:</th>
                                    <td><input type="text" class="form-control" size="20" v-model="detail_group_name" disabled /></td>
                                </tr>
                                <tr height="45">
                                    <th style="text-align:right;padding-right:10px;">组内权限:</th>
                                    <td style="font-size:12px;">
                                        <div class="funcs_box" style="overflow-y:scroll;height:400px;padding:5px 10px; margin:10px 0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;border-left:1px solid #ccc;">
                                        <?php
                                        foreach($all_funcs as $cate_1 => $f) {
                                            echo '<div style="font-size:14px;font-weight:bold;margin-bottom:1px;">' . $cate_1 . '</div>';
                                            foreach($f as $cate_2 => $ff) {
                                                echo '<div style="border-bottom:1px solid #eee;margin:0;padding:0;margin-bottom:1px;">';
	                                            echo '<div style="width:150px;" class="pull-left">　　|—　' . $cate_2 . '</div>';
	                                            echo '<div class="pull-left">';
	                                            foreach($ff as $cate_3 => $fff) {
		                                            echo '<label style="margin-right:15px;display:inline-block;">';
		                                            echo '<input type="checkbox" disabled class="minimal" v-model="detail_group_funcs" value="'.$fff.'"> ';
		                                            echo $cate_3;
		                                            echo '</label>';
	                                            }
	                                            echo '</div>';
	                                            echo '<div style="clear:both"></div>';
                                                echo '</div>';
                                            }
                                        }
                                        ?>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

</section>

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/vue.min.js"></script>
<script src="js/pace.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>

<script type="text/javascript">
    var app = new Vue({
        el: '#vbody',
        data: {
            // 全局
            all_func_ids: $.parseJSON('<?php echo json_encode($func_ids); ?>'),

            new_group_name: '',
            new_group_funcs: [],

            detail_group_name: '',
            detail_group_funcs: []
        },
        methods: {
            submitAddGroup: function() {
                if(!this.new_group_name) { alert('组名不可为空'); return false; }
                var go = true;
                if(this.new_group_funcs.length < 1) {
                    if(confirm('确定要创建一个没有任何权限的账号吗?')) {
                        go = true;
                    } else {
                        go = false;
                    }
                }
                if(go === true) {
                    location.href = 'super_group.php?action=new_group&name=' + this.new_group_name + '&funcs=' + this.new_group_funcs.join(',');
                }
            },
            delGroup: function(gid, gnum) {
                if(gnum > 0) {
                    alert('该分组下属用户大于0, 不可删除, 请更改下属用户分组后再进行删除操作'); return false;
                }
                if(confirm('确定要删除这个分组吗?')) {
                    location.href = 'super_group.php?action=del&gid=' + gid;
                }
            },
            funcsDetail: function(gname, gfuncs) {
                this.detail_group_name = gname;
                this.detail_group_funcs = gfuncs.split(',');
            }
        }
    });

    $('#modal-add-admin').on('hidden.bs.modal', function() {
        app.new_group_name = '';
        app.new_group_funcs = [];
    });
    $('#modal-funcs-detail').on('hidden.bs.modal', function() {
        app.detail_group_name = '';
        app.detail_group_funcs = [];
    });

    $(function() {
        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);
    });
</script>

</body>
</html>
